package com.canplay.screen.repository

import android.util.Log
import com.canplay.screen.common.ConstClass
import com.canplay.screen.common.ConstClass.Companion.LOG_TAG
import com.canplay.screen.db.DataItem
import com.canplay.screen.db.DataLocateDataSource
import com.canplay.screen.mode.DataInfo
import com.canplay.screen.network.ApiService
import com.canplay.screen.response.AllDateResponse
import com.canplay.screen.response.BaseResponse
import com.canplay.screen.response.NumResponse
import com.canplay.screen.response.RequestCallback
import com.canplay.screen.response.Response
import com.canplay.screen.utils.ToastUtils
import com.google.gson.Gson
import io.reactivex.rxjava3.core.Flowable
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class MyRepository(
    private val apiService: ApiService, private var dataLocateDataSource: DataLocateDataSource
) {
    suspend fun getVersionInfo(): Response<Long>? {
        try {
            return apiService.selectVersion()
        } catch (e: Exception) {
            return null;
        }
    }

    fun getAllDate(requestCallback: RequestCallback) {
        GlobalScope.launch(Dispatchers.IO) {
            val call = apiService.downloadData();
            try {
                val response = call.execute()
                if (response.isSuccessful) {
                    val responseBody = response.body()
                    responseBody?.let { body ->
                        val inputStream = body.byteStream()
                        inputStream.use { input ->
                            // 逐行处理输入流
                            input.bufferedReader().useLines { lines ->
                                lines.forEach { line ->
                                    // 处理每一行数据
                                    Log.d(LOG_TAG, "下载数据成功:$line")
                                    val dataInfo =
                                        Gson().fromJson(line, AllDateResponse::class.java)
                                    if (dataInfo.isSuccess()) {
                                        val projectList = dataInfo.data.projectList
                                        if (projectList?.size!! > 0) {
                                            //先清掉数据库
                                            dataLocateDataSource.deleteAll();
                                        }
                                        val showData = ArrayList<DataItem>()
                                        projectList?.forEach { item ->
                                            var itemData = DataItem(
                                                item.id,
                                                item.remark,
                                                item.projectName,
                                                item.projectPrice,
                                                item.unit,
                                                item.department,
                                                item.chargeBasis,
                                                item.versionId,
                                                item.updateTime,
                                            )
                                            showData.add(itemData)

                                        }
                                        dataLocateDataSource.insertAll(showData);
                                        withContext(Dispatchers.Main) {
                                            // 在主线程中更新 UI 或处理结果
                                            Log.d(LOG_TAG, "下载处理完成,共${showData.size}条:")
                                            requestCallback.isSuccess(showData)
                                        }

                                    } else {
                                        withContext(Dispatchers.Main) {
                                            requestCallback.isFail()
                                        }
                                    }
                                }
                            }
                        }
                    }
                } else {
                    Log.d(LOG_TAG, "Download failed: ${response.code()}")
                    withContext(Dispatchers.Main) {
                        requestCallback.isFail()
                    }
                }
            } catch (e: Exception) {
                Log.d(LOG_TAG, "Download failed: ${e.message}")
                withContext(Dispatchers.Main) {
                    requestCallback.isFail()
                }
            }

        }
    }
}